/**
 * 线程死锁例程
 */
package thread;

public class J_Lock extends Thread {
    public static Object m_objectA = new Object();
    public static Object m_objectB = new Object();

    J_Lock(String s) {
        super(s);
    }

    public static void mb_sleep() {
        try {
            Thread.sleep((int) (Math.random() * 1000));
        } catch (InterruptedException e) {
            System.out.println("异常 InterruptedException：" + e);
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        boolean t = true;
        System.out.println(getName() + "开始运行");
        while (true) {
            t = !t;
            synchronized (t ? m_objectA : m_objectB) {

                System.out.println(getName() + "：" + (t ? "对象A" : "对象B") + "被锁住1");
                mb_sleep();
                synchronized (t ? m_objectB : m_objectA) {
                    System.out.println(getName() + "：" + (t ? "对象B" : "对象A") + "被锁住2");
                    mb_sleep();
                    System.out.println(getName() + "：" + (t ? "对象B" : "对象A") + "的锁被打开");
                }
                System.out.println(getName() + "：" + (t ? "对象A" : "对象B") + "的锁被打开");
            }
        }
    }

    public static void main(String args[]) {
        J_Lock t1 = new J_Lock("线程1");
        J_Lock t2 = new J_Lock("线程2");
        t1.start();
        t2.start();
    }
}
